package com.crazymakercircle.imServer.test;

import com.crazymakercircle.util.ThreadUtil;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;

/**
 * @Description
 * @Date 2021/7/22
 * @Created by Jonathan
 */
public class CallBackScheduler {
    //方法二是使用自建的线程池时，专用于处理耗时操作
    static ListeningExecutorService gPool = null;

    static {
        ExecutorService jPool = ThreadUtil.getMixedTargetThreadPool();
        gPool = MoreExecutors.listeningDecorator(jPool);
    }


    // 构造函数
    private CallBackScheduler() {

    }

    //添加任务
    public static <R> void add(TaskDemo<R> task) {
        ListenableFuture<R> future = gPool.submit(new Callable<R>() {
            public R call() throws Exception {
                R r = task.execute();
                return r;
            }

        });

        Futures.addCallback(future, new FutureCallback<R>() {
            public void onSuccess(R r) {
                task.onSuccess(r);
            }

            public void onFailure(Throwable t) {
                task.onFailure(t);
            }
        });
    }
}
